﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FilStartUps.DAL;
using System.Data;
using System.Data.SqlTypes;

namespace FilStartUps.Helper
{

    public class SessionHelper
    {

        public static void CreateSession(int userid)
        {
            using (FilStartUpsEntities db_connect = new FilStartUpsEntities())
            {
                try
                {
                    Session session = new Session();
                    session.memberidFK = userid;
                    session.session_flag = true;
                    session.sessiondatelogon = DateTime.Now;
                    session.sessiondatelogout = Convert.ToDateTime(SqlDateTime.MinValue.Value);
                    db_connect.Sessions.Add(session);
                    db_connect.SaveChanges();
                }
                catch (Exception e)
                {
                    string sample = e.ToString();
                }
            }
        }
        public static void UpdateSession(int userid)
        {
            using (FilStartUpsEntities db_connect = new FilStartUpsEntities())
            {
                var updatesession = db_connect.Sessions.Where(s => s.memberidFK.Equals(userid) && s.session_flag.Equals(true)).SingleOrDefault();
                updatesession.sessiondatelogon = DateTime.Now;
                db_connect.Entry(updatesession).State = EntityState.Modified;
                db_connect.SaveChanges();
            }
        }
        public static bool CheckSession(int userid)
        {
            using (FilStartUpsEntities db_connect = new FilStartUpsEntities())
            {
                var checksession = db_connect.Sessions.Where(s => s.session_flag.Equals(true) && s.memberidFK.Equals(userid)).SingleOrDefault();
                if (checksession != null)
                {
                    //Existing Session
                    return true;
                }
                else
                {
                    //Create New Session
                    return false;
                }
            }
        }
        public static void AbandonSession(int userid)
        {
            using (FilStartUpsEntities db_connect = new FilStartUpsEntities())
            {
                var abandonsession = db_connect.Sessions.Where(s => s.memberidFK.Equals(userid) && s.session_flag.Equals(true)).SingleOrDefault();
                abandonsession.session_flag = false;
                abandonsession.sessiondatelogout = DateTime.Now;
                db_connect.Entry(abandonsession).State = EntityState.Modified;
                db_connect.SaveChanges();
            }
        }
    }
}